<template>
  <div v-loading="loading">
    <div class="moveFile">
      <div class="treeData" style="height: 100%;">
        <div style="height: 76%;overflow: auto;">
          <el-tree
            ref="tree"
            class="filter-tree tree-file"
            :data="data"
            :props="defaultProps"
            lazy
            :load="loadNode"
            :default-expand-all="false"
            :expand-on-click-node="false"
            :highlight-current="true"
            :indent="10"
          >
            <span slot-scope="{node, data}" class="custom-tree-node" @click="() => choiceFolder(data)">
              <div class="rows" style="-webkit-user-select:none">
                <span :title="data.name" class="titTree">
                  <i :class="(data.isBuiltIn === '1' || data.fileLibraryRole.permission === 'view') ? 'el-icon-fail-fold' : 'el-icon-fold'" />
                  <span>{{ data.name }}</span>
                </span>
              </div>
            </span>
          </el-tree>
        </div>
        <div v-if="filterText">
          <hr>
          <el-form ref="form" :model="form" :rules="rules" style="position: unset;height: 26%;margin-top: 20px;">
            <p class="title" style="margin-top: 0px;border: 1px solid #DCDFE6;height: 30px;line-height: 2;" v-html="filterText" />
            <span style="display: none">{{ form.businessId }} - {{ subjectType }} - {{ selectBusType }}</span>
            <el-form-item v-if="isShowSubjectType" prop="businessId" style="margin-bottom: 0px;">
              <MainBodySelect v-model="form.businessId" :width="'100%'" :show-label="true" :parameters="subjectType" :select-bus-type="selectBusType" />
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <!--操作按钮-->
    <div class="dialog-footer" style="text-align: right;">
      <el-checkbox v-model="whetherToShowAllDirectoriesBtn" style="margin: 0 30px;" @change="whetherToShowAllDirectoriesMethod">{{ $t('展示所有文件夹') }}</el-checkbox>
      <el-button @click="cancel">{{ $t("取消") }}</el-button>
      <el-button type="primary" :disabled="folderId === undefined || folderId === null || folderId === ''" @click="submitForm">{{ $t("保存") }}</el-button>
    </div>
  </div>
</template>
<script>
  import {
    findLeftList,
    moveFileToOther,
    copyFileToOther,
    bulkMoveFile
  } from '@/api/file/filefolder/folder.js'
  import { getLpView } from '@/api/base/deal/dealBase'
  import MainBodySelect from '@/components/MainBodySelect'
  import { getArrayByCode } from '@/api/file/directoryRelatedBusiness/directoryRelatedBusiness'
  export default {
    components: {
      MainBodySelect
    },
    data() {
      return {
        loading: false,
        filterText: '',
        fileNameSearch: '',
        defaultProps: {},
        // 表单参数
        form: {
          businessId: undefined
        },
        data: [],
        // 表单校验
        rules: {
          businessId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
        },
        // 要移动复制到该文件夹下
        folderId: '',
        // 要被移动复制的文件
        file: {
          businessId: undefined
        },
        subjectType: '',
        isShowSubjectType: false,
        // 是那种业务类型
        businessType: '',
        // 是否显示全部目录
        whetherToShowAllDirectories: false,
        whetherToShowAllDirectoriesBtn: false,
        // 操作信号.本次打开磁组件的目的:  copy:复制, move: 移动, bulkMove: 批量移动
        operatingSignal: undefined,
        // 要被批量移动或复制的文件数组
        operationFileList: [],
        // 项目类型
        selectBusType: undefined,
        businessIdAuto: this.$route.query.id === undefined ? (this.$route.query.lpId === undefined ? undefined : this.$route.query.lpId) : this.$route.query.id
      }
    },
    watch: {
      fileNameSearch(val) {
        this.$refs.tree.filter(val)
      }
    },
    mounted() {
    },
    created() {
      this.$bus.$emit('async_done')
    },
    methods: {
      init(data) {
        this.loading = true
        this.selectBusType = ''
        this.defaultExpandAll = false
        // 初始化一下重新打开时,页面残留参数
        this.filterText = ''
        this.form.businessId = data.businessId
        this.subjectType = ''
        this.file = data
        this.whetherToShowAllDirectoriesBtn = false
        console.log(this.file)
        if (this.file.businessId !== '' && this.file.businessId !== undefined && this.file.businessId !== null) {
          this.whetherToShowAllDirectories = true
          this.findLeftList()
        } else {
          this.whetherToShowAllDirectories = false
          this.findLeftListAll('')
        }
      },
      /**
       * 批量操作
       *    批量移动: 文档库页面会先排除 data_id有值 这些文件是绑在表单或绑定到项目上的.
       */
      bulkInit(fileList, businessId) {
        this.loading = false
        this.selectBusType = ''
        this.operationFileList = fileList
        // 准备加载页面数据
        console.log(fileList, businessId, this.businessType)
        if (this.operatingSignal === 'bulkMove') { // 批量移动
          this.loading = true
          this.defaultExpandAll = false
          // 初始化一下重新打开时,页面残留参数
          this.filterText = ''
          this.form.businessId = ''
          this.subjectType = ''
          this.whetherToShowAllDirectoriesBtn = false
          if (businessId !== undefined && businessId !== null && businessId !== '') {
            this.form.businessId = businessId
            this.whetherToShowAllDirectories = true
            this.findLeftList()
          } else {
            this.whetherToShowAllDirectories = false
            this.findLeftListAll('')
          }
        } else if (this.operatingSignal === 'bulkCopy') { // 批量复制
        }
      },
      findLeftListAll(belong) {
        this.loading = true
        findLeftList({ id: belong, belong: belong, businessId: this.businessIdAuto, parentId: '0' }).then(response => {
          if (response.code === 200) {
            this.data = []
            if (this.businessType === '') {
              this.data = response.data
            } else {
              this.data = response.data
            }
          }
          this.loading = false
        })
      },
      findLeftList() {
        getLpView(this.form.businessId).then(responseLP => {
          this.queryCount = 0
          if (responseLP.data.length > 0) {
            // 根据这个类型去除对应的项目目录
            var type = responseLP.data[0].dealType
            var belong
            // 批量选择时的判断. 是否为dataRoom
            if (this.operationFileList !== undefined && this.operationFileList !== null && this.operationFileList.length > 0) {
              belong = this.operationFileList[0].belong
            }
            // 单独选择时的判断. 是否为dataRoom
            if (belong === undefined) {
              belong = this.file.belong
            }
            // 判断操作
            if (type === 'fund' && belong === 'data_room') {
              type = 'data_room'
            }
            // if (['equity', 'debt', 'bf'].includes(type)) {
            //   this.mainBodyChoice = 'deal'
            // } else if (['fund'].includes(type)) {
            //   this.mainBodyChoice = 'fund'
            // } else if (['manager'].includes(type)) {
            //   this.mainBodyChoice = 'manager'
            // } else if (['hhqy'].includes(type)) {
            //   this.mainBodyChoice = 'hhqy'
            // } else if (['GR', 'GP'].includes(type)) {
            //   this.mainBodyChoice = 'lpInvestor'
            // } else {
            //   console.log('默认加载股权')
            //   type = 'equity'
            // }
            /** 注释的这段代码尽量不要删除. 用于数据参考 */
            console.info('初始化... 加载当前业务类型文件夹...')
            this.elementLoadingText = this.$t('正在加载特定文件类型...')
            if (this.businessType === undefined || this.businessType === null || this.businessType === '') {
              // 替换了上面注释内容
              getArrayByCode('vueUpload_directorySwitch').then(response => {
                const vueUploadDirectorySwitch = response.data
                if (vueUploadDirectorySwitch !== undefined && vueUploadDirectorySwitch !== null && vueUploadDirectorySwitch !== '') {
                  const object = vueUploadDirectorySwitch.find(obj => obj.busType === type)
                  if (object) {
                    this.$nextTick(() => {
                      this.selectBusType = object.busType
                      // 项目类型. dealType....
                      if (object.busOther !== '' && object.busOther !== null) {
                        this.mainBodyChoice = object.busOther
                      }
                      this.$forceUpdate()
                    })
                  } else {
                    type = 'equity'
                  }
                } else {
                  type = 'equity'
                }
              })
            } else {
              type = this.businessType
            }
            this.findLeftListAll(type)
          } else {
            this.loading = false
          }
        })
      },
      loadNode(node, resolve) {
        var businessIdQuery = this.businessIdAuto
        if (this.isEmpty(businessIdQuery)) {
          businessIdQuery = this.$route.query.id
        }
        this.loading = true
        findLeftList({ id: this.businessType, businessId: businessIdQuery, parentId: node.data.id, belong: node.data.belong }).then(response => {
          resolve(response.data)
          this.loading = false
        })
      },
      // 据目录Id只查询目录
      choiceFolder(data) {
        if (data.isBuiltIn !== '1' && data.fileLibraryRole.permission !== 'view') {
          this.folderId = data.id
          if (this.file.name) {
            this.filterText = '<span style="color: #1ab394">' + this.file.name + '</span>  ' + this.$t('将会移动或复制到') + ' [<span style=\'color: red\'>' + data.name + '</span>] ' + this.$t('目录下')
          } else {
            var msg = ''
            if (this.operationFileList !== undefined && this.operationFileList !== null && this.operationFileList.length > 0) {
              this.operationFileList.forEach(item => {
                msg += item.name + '&#10;'
              })
            }
            this.filterText = '<span style="color: #1ab394">' + this.$t('文件批量移动或复制到') + ' [<span style=\'color: red\'>' + data.name + '</span>] ' + this.$t('目录下') + '<i title="' + msg + '" class="el-icon-question" />'
          }
          this.mainBodyType(data)
        }
      },
      // 保存
      submitForm() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.loading = true
            if (this.operatingSignal === 'copy' || this.operatingSignal === 'move' || this.operatingSignal === undefined) {
              // 文件 操作类型
              if (this.file.id === undefined || this.file.id === null || this.file.id === '' ||
                this.folderId === undefined || this.folderId === '' || this.folderId === null) {
                this.msgError(this.$t('请先选择文件夹'))
                this.loading = false
              } else {
                if (this.file.operationType === 'move') {
                  moveFileToOther({
                    id: this.file.id,
                    directoryId: this.folderId,
                    businessId: this.form.businessId
                  }).then(response => {
                    this.getResponseTo(response)
                    this.loading = false
                  })
                } else {
                  copyFileToOther({
                    id: this.file.id,
                    directoryId: this.folderId,
                    businessId: this.form.businessId
                  }).then(response => {
                    this.getResponseTo(response)
                    this.loading = false
                  })
                }
              }
            } else if (this.operatingSignal === 'bulkMove' || this.operatingSignal === 'bulkCopy') {
              if ((this.folderId === undefined || this.folderId === '' || this.folderId === null) ||
                (this.operationFileList === undefined || this.operationFileList === null || this.operationFileList.length <= 0)) {
                console.info('要批量移动的文件数量:' + this.operationFileList.length)
                this.msgError(this.$t('请先选择文件夹'))
                this.loading = false
              } else {
                if (this.operatingSignal === 'bulkMove') {
                  bulkMoveFile({ businessId: this.form.businessId, directoryId: this.folderId, fileList: this.operationFileList }).then(response => {
                    this.getResponseTo(response)
                    this.loading = false
                  })
                }
              }
            }
          }
        })
      },
      // 是否切换到显示所有可上传目录
      whetherToShowAllDirectoriesMethod() {
        console.log('切换')
        this.whetherToShowAllDirectories = !this.whetherToShowAllDirectories
        if (this.whetherToShowAllDirectories) {
          this.findLeftList()
        } else {
          this.findLeftListAll()
        }
      },
      getResponseTo(response) {
        if (response.code === 200) {
            this.msgSuccess(response.msg)
            // 重新加载页面
            this.$parent.$parent.findFileListByFolderIdMethod()
            this.cancel()
        } else {
          this.msgError(this.$t(response.data.msg))
        }
      },
      // 取消按钮
      cancel() {
        this.$parent.$parent.formOpenMove = false
      },
      mainBodyType(data) {
        if (this.form.businessId === undefined || this.form.businessId === null || this.form.businessId === '') {
          this.form.businessId = this.$route.query.id
        }
        if (data.belong === 'debt_items') {
          this.subjectType = 'deal'
          this.isShowSubjectType = true
        } else if (data.belong === 'equity_deal') {
          this.subjectType = 'deal'
          this.isShowSubjectType = true
        } else if (data.belong === 'equity_fund') {
          this.subjectType = 'deal'
          this.isShowSubjectType = true
        } else if (data.belong === 'fund') {
          this.subjectType = 'fund'
          this.isShowSubjectType = true
        } else if (data.belong === 'data_room') {
          this.subjectType = 'fund'
          this.isShowSubjectType = true
        } else if (data.belong === 'investor_doc') {
          this.subjectType = 'lpInvestor'
          this.isShowSubjectType = true
        } else if (data.belong === 'spv') {
          this.subjectType = 'spv'
          this.isShowSubjectType = true
        } else if (data.belong === 'estate_deal') {
          this.subjectType = 'deal'
          this.isShowSubjectType = true
        } else {
          this.isShowSubjectType = false
          this.form.businessId = undefined
        }
      }
    }
  }
</script>
